<template>
  <section>
    <el-form ref="addForm" :model="addform" label-width="80px" @submit.prevent="onSubmit"
             style="margin:20px;min-width:600px;">
      <el-form-item label="卡片名称">
        <template slot-scope="scope">
          <div style="width: 300px;display: inline-block;">
            <el-input v-model="addform.title" auto-complete="on"></el-input>
          </div>
        </template>
      </el-form-item>
      <el-form-item label="卡片描述">
        <template>
          <div style="width: 600px;">
            <el-input type="textarea" v-model="addform.description"></el-input>
          </div>
        </template>
      </el-form-item>

      <el-form-item label="总次数">
        <template slot-scope="scope">
          <div style="width: 300px;display: inline-block;">
            <el-input v-model="addform.shipping_number" auto-complete="on"></el-input>
          </div>
          <span>（单位：次）</span>
          <span style="color: #48576A;">例如：8(次)-输入数字</span>
        </template>
      </el-form-item>
      <el-form-item label="配送时间">
        <el-checkbox-group v-model="checkedPurview" @change="purviewCheckedChange">
          <el-checkbox v-for="(pur, key) in purviewName" :label="pur" :key="key" style="margin-right: 10px;margin-top: 10px;" ref="checkPurbox">{{ purviewName[key].name }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="库存">
        <template slot-scope="scope">
          <div style="width: 300px;display: inline-block;">
            <el-input v-model="addform.inventory" auto-complete="on"></el-input>
          </div>
          <span>（单位：份）</span>
          <span style="color: #48576A;">例如：30(份)-输入数字</span>
        </template>
      </el-form-item>

      <el-form-item label="售价">
        <template slot-scope="scope">
          <div style="width: 300px;display: inline-block;">
            <el-input v-model="addform.price" auto-complete="on"></el-input>
          </div>
          <span>（单位：元）</span>
          <span style="color: #48576A;">例如：59(元)-输入数字</span>
        </template>
      </el-form-item>

      <el-form-item label="标价">
        <template slot-scope="scope">
          <div style="width: 300px;display: inline-block;">
            <el-input v-model="addform.orgin_price" auto-complete="on"></el-input>
          </div>
          <span>（单位：元）</span>
          <span style="color: #48576A;">例如：59(元)-输入数字</span>
        </template>
      </el-form-item>
      <el-form-item label="是否在售">
        <template>
          <div style="width: 300px;display: inline-block;">
            <el-select v-model="addform.is_sale" placeholder="请选择">
              <el-option
                v-for="item in saleList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
        </template>
      </el-form-item>
      <el-form-item label="附加属性">
        <div class="addAttr">
          <span class="attr" @click="addDomain">添加+</span>
        </div>
        <el-form>
          <el-form-item
            v-for="(domain, index) in attrList"
            :key="domain.key"
            :prop="'attrList.' + index + '.k'">
            <el-input v-model="domain.k" style="display: inline-block;width: 150px;margin-right: 20px;margin-top:10px;"></el-input>
            <el-input v-model="domain.v" style="display: inline-block;width: 150px;margin-top:10px;"></el-input>
            <el-button @click.prevent="removeDomain(index)">删除</el-button>
          </el-form-item>
        </el-form>
      </el-form-item >
      <el-form-item label="配送内容">
        <template slot-scope="scope">
          <div style="width: 300px;display: inline-block;">
            <el-input v-model="expressThing" auto-complete="on"></el-input>
          </div>
        </template>
      </el-form-item>
      <el-form-item label="商品重量">
        <template slot-scope="scope">
          <div style="width: 150px;display: inline-block;">
            <el-input v-model="weight" auto-complete="on"></el-input>
          </div>
          <div style="width: 150px;display: inline-block;">
            <el-select v-model="unit" placeholder="请选择">
              <el-option
                v-for="item in unitList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
        </template>
      </el-form-item>
      <el-form-item label="配送次数">
        <template slot-scope="scope">
          <div style="width: 300px;display: inline-block;">
            <el-input v-model="expressNumber" auto-complete="on"></el-input>
          </div>
          <span style="color: #48576A;">例如：一周两次</span>
        </template>
      </el-form-item>
      <el-form-item label="列表图片">
        <template>
          <div class="p-listPic-upload">
            <el-button type="success">上传<i class="el-icon-upload el-icon--right"></i></el-button>
            <span class="upload_plant_pic"><input type="file" name="file" class="cfg_upload_pic" @change="upInputOnchange"></span>
          </div>
          <div style="width: 120px;height: 80px; background: #ffffff;overflow: hidden;margin-top: 20px" v-if="addform.list_img">
            <img :src="addform.list_img" />
          </div>
        </template>
      </el-form-item>

      <el-form-item label="详情图片">
        <template>
          <div class="p-listPic-upload">
            <el-upload drag action="/index.php?c=plant&a=uploadDetailPic" multiple :on-success="uploadSuccess" :on-remove="removePic">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过5000kb</div>
            </el-upload>
          </div>
          <div style="background: #ffffff;overflow: hidden;margin-top: 20px" v-if="addform.detail_img">
            <img v-for="(item, index) in addform.detail_img" :src="item.url" style="width: 120px;height: 80px;margin-right: 5px;" :key="index"/>
          </div>
        </template>
      </el-form-item>

      <el-form-item label="卡片详情">
        <editer ref="editer"></editer>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click.native="addcards">立即创建</el-button>
      </el-form-item>

    </el-form>
  </section>
</template>

<script type="text/ecmascript-6">
  import { apiTree } from '../../apiTree'
  import NProgress from 'nprogress'
  import util from '../../util'
  import editer from '../common/ueditor'
  import { returnEditerHtml } from '../../vuex/getters'

  export default {
    components: {
      editer
    },
    data() {
      return {
        checkedPurview: [],
        checkedArr: '',
        purviewName: [
          {'name': '星期一', 'value': '1'},
          {'name': '星期二', 'value': '2'},
          {'name': '星期三', 'value': '3'},
          {'name': '星期四', 'value': '4'},
          {'name': '星期五', 'value': '5'},
          {'name': '星期六', 'value': '6'},
          {'name': '星期日', 'value': '0'}
        ],
        expressThing: '',
        expressNumber: '',
        unit: '',
        unitList: [
          {'value': 'kg', 'label': 'kg'},
          {'value': 'g', 'label': 'g'}
        ],
        showcards: false,
        attrList: [],
        category: [],
        options: [],
        saleList: [
          {'value': '1', 'label': '在售'},
          {'value': '0', 'label': '下架'}
        ],
        weight: '',
        user: '',
        addform: {
          title: '',
          description: '',
          content: '',
          list_img: '',
          detail_img: [],
          card_attr: [],
          orgin_price: '',
          price: '',
          isIndeterminate: true,
          shipping_week: '',
          shipping_number: '',
          inventory: '',
          is_sale: '1'
        },
        fileList: []
      }
    },
    methods: {
      // 修改卡片属性逻辑
      removeDomain(index) {
        this.attrList.splice(index, 1)
      },
      // 全部选中时候，再选中全选
      purviewCheckedChange(value) {
        let arr = [];
        for (let i = 0; i < this.checkedPurview.length; i++) {
          arr.push(this.checkedPurview[i].value);
        }
        arr.sort();
        if (arr[0] === '0') {
          arr.splice(0, 1)
          arr.push('0');
        }
        this.checkedArr = arr.join(',');
      },
      addDomain() {
        this.attrList.push({
          k: '',
          v: '',
          key: Date.now()
        });
      },
      // 上传卡片照片
      upInputOnchange(e) {
        var _that = this
        let file = e.target.files[0]
        let _reader = new FileReader()
        _reader.readAsDataURL(file)
        _reader.onload = function() {
          let _file = this.result
          let param = {'file': _file, 'type': 3}
          apiTree('upload/index', 'plant/upload', param, 'POST').then((res) => {
            if (res.s === 1) {
              _that.addform.list_img = res.d.url
            }
          })
        }
      },
      uploadSuccess(res, _file) {
        if (res.s === 1) {
          this.addform.detail_img.push({type: 1, url: res.d.url})
        }
      },
      removePic(_file) {
        this.addform.detail_img.forEach((item, key) => {
          if (_file.name === item.name) {
            this.addform.detail_img.splice(key, 1)
          }
        })
      },
      addcards: function () {
        this.$confirm('确认提交吗？', '提示', {}).then(() => {
          this.$refs.editer.$emit('getUeditorContent')
          this.addform.content = returnEditerHtml(this.$store.state);
          NProgress.start();
          // 此处需要添加逻辑判断  谨慎验证属性添加部分
          if (util.isEmpty(this.weight) || util.isEmpty(this.unit) || util.isEmpty(this.expressThing) || util.isEmpty(this.expressNumber)) {
            this.$message.error('请填写完固定属性');
            return ;
          }
          if (util.isEmpty(this.addform.title)) {
            this.$message.error('请填写标题');
            return ;
          }
          if (!util.isNumber(this.addform.price) || !util.isNumber(this.addform.orgin_price)) {
            this.$message.error('价格应为数字');
            return ;
          }
          if (!util.isNumber(this.addform.inventory)) {
            this.$message.error('库存应为数字');
            return ;
          }
          if (!util.isNumber(this.addform.shipping_number)) {
            this.$message.error('总次数应为数字');
            return ;
          }
          if (util.isEmpty(this.addform.description)) {
            this.$message.error('卡片描述不能为空');
            return ;
          }
          if (util.isEmpty(this.addform.list_img)) {
            this.$message.error('列表图片不能为空！')
            return
          }
          if (util.isEmpty(this.addform.detail_img)) {
            this.$message.error('相册图片不能为空！')
            return
          }
          this.addform.shipping_week = this.checkedArr;
          if (util.isEmpty(this.addform.shipping_week)) {
            this.$message.error('发货周期请填写');
            return ;
          }
          let ub = this.weight + this.unit;
          this.attrList.push({ 'k': '配送内容', 'v': this.expressThing });
          this.attrList.push({ 'k': '商品重量', 'v': ub });
          this.attrList.push({ 'k': '配送次数', 'v': this.expressNumber });
          this.addform.cards_attr = this.attrList;

          apiTree('cards/index', 'cards/setcards', this.addform, 'POST').then((res) => {
            if (res.s === 1) {
              NProgress.done();
              this.$message({
                message: '提交成功',
                type: 'success'
              });
              this.$router.push('/cards/index');
            } else {
              this.$message.error(res.err_str)
            }
          })
        })
      }
    }
  }

</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
  .p-listPic-upload
    display inline-block
    margin-left 10px
    position relative
    cursor pointer
    .upload_plant_pic
      display block
      width 80px
      height 35px
      cursor pointer
      position absolute
      top 0px
      left 0px
      opacity 0
      & input[type=file]
        display block
        cursor pointer
        width 80px
        height 35px
  .p-pic-old-input
    display inline-block
    width 500px
  .addAttr
    width 100%
    height 50px
    .attr
      color #00b7ee
  .attrBList
    width 100%
    height 50px
    border-bottom #333333 1px solid
    & span
      display inline-block
      width 130px
      line-height 50px
      color #666666
</style>
